package com.guslegend.service.impl;

import com.guslegend.component.MailService;
import com.guslegend.constant.CacheKey;
import com.guslegend.enums.BizCodeEnum;
import com.guslegend.enums.SendCodeEnum;
import com.guslegend.service.NotifyService;
import com.guslegend.util.CheckUtil;
import com.guslegend.util.CommonUtil;
import com.guslegend.util.JsonData;
import com.guslegend.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: guslegend
 * @description: 邮件发送
 * @create: 2025-05-26 07:47
 **/
@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {
    @Autowired
    private MailService mailService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 验证码内容
     */
    private static final String CONTENT = "您的验证码是：%s,有效时间是60秒";
    /**
     * 验证码有效时间
     */
    private static final int CODE_EXPIRE = 1000 * 60 * 10;

    /**
     * @Description: 发送邮箱验证码 存储到缓存
     */
    @Override

    public JsonData sendCode(SendCodeEnum sendCodeEnum, String to) {
        //缓存key
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
        //        根据缓存key拿到缓存值
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);

        //缓存值是否存在 是否超过了60s
        if (StringUtils.isNotBlank(cacheValue)) {
//            拿到缓存值的时间戳 与当前时间戳比较是否超过有效期
            long cacheValueTimeMills = Long.parseLong(redisTemplate.opsForValue().get(cacheKey).split("-")[1]);
            long time = CommonUtil.getCurrentTimeMillis() - cacheValueTimeMills;
            if (time < CODE_EXPIRE) {
                log.info("{}重复发送验证，时间间隔{}毫秒", to, time);
                return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
            }
        }

        //        生成随机验证码
        String code = RandomUtil.getSixBitRandom();
//        拼接存到redis中的值
        String value = code + "-" + CommonUtil.getCurrentTimeMillis();
//        存储到缓存
        redisTemplate.opsForValue().set(cacheKey, value, CODE_EXPIRE, TimeUnit.MILLISECONDS);
        //        发送邮箱验证码
        if (CheckUtil.isEmail(to)) {
            try {
                mailService.sendSimpleMail(to, sendCodeEnum.getSubject(), String.format(CONTENT, code));
            } catch (Exception e) {
                return JsonData.buildError("邮件发送失败");
            }
            return JsonData.buildSuccess();
        } else if (CheckUtil.isPhone(to)) {
            //发送手机验证码
            //            TODO
            return null;
        } else {
            return JsonData.buildResult(BizCodeEnum.CODE_TO_ERROR);
        }
    }

    @Override
    public boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
        //缓存key
        String cacheKey = String.format(CacheKey.CHECK_CODE_KEY, sendCodeEnum.name(), to);
        String redisCode = redisTemplate.opsForValue().get(cacheKey);
        log.info("用户{} 验证码{}", to, redisCode);
        if (StringUtils.isNotBlank(redisCode)) {
//            判断验证码是否正确
            if (redisCode.substring(0, redisCode.lastIndexOf("-")).equals(code)) {
                redisTemplate.delete(cacheKey);
                return true;
            }
        }
        return false;
    }
}
